/******************************************************************
 * Copyright @ 2024 广州牛师帮科技文化有限公司. All rights reserverd.
 * @file   src\utils\CopyGuard.ts
 * @author Gim
 * @date   2024/12/28 14:07
 * @desc   复制的限制
 * @keyword 拷贝,复制,限制
 ******************************************************************/

class CopyGuard {
  get running() { return !!this._timer_id }
  set running(v: boolean) { v ? this.run() : this.stop() }
  protected _disabled: boolean = false;
  protected _timer_id: number = 0;
  protected _skip_element_classname_set = new Set<string>();
  protected _skip_element_id_set = new Set<string>();
  protected _skip_elements_set = new Set<Element>();
  add_element(...elements: Element[]) {
    for (const element of elements)
      this._skip_elements_set.add(element);
  }
  add_element_id(...element_ids: string[]) {
    for (const element_id of element_ids)
      this._skip_element_id_set.add(element_id);
  }
  add_classnames(...classnames: string[]) {
    for (const element_id of classnames)
      this._skip_element_classname_set.add(element_id);
  }
  protected is_skip_element(ele: Element): boolean {
    if (!ele) return true;
    if (ele.tagName === 'INPUT') return true;
    for (const element_id of this._skip_element_id_set)
      if (ele.id === element_id)
        return true;
    for (const classname of this._skip_element_classname_set)
      if (ele.classList?.contains(classname))
        return true;
    return false;
  }
  run() {
    clearInterval(this._timer_id);
    const fn = (e: Event) => {
      let ele = (e.target as Element | null);
      while (ele) {
        if (this.is_skip_element(ele))
          return;
        ele = ele.parentElement;
      }
      return e.returnValue = false;
    };
    this._timer_id = window.setInterval(() => {
      document.oncontextmenu = fn;
      document.onselectstart = fn;
      document.oncopy = fn;
    }, 1);
  }
  stop() {
    clearInterval(this._timer_id);
    document.oncontextmenu = null;
    document.onselectstart = null;
    document.oncopy = null;
    this._timer_id = 0;
  }
}
export default new CopyGuard()